package com.xingda.packing.http;

import com.alibaba.fastjson.JSONObject;
import com.xingda.packing.common.PackUtils;
import com.xingda.packing.config.appset.AppSetUrl;
import com.xingda.packing.domain.Wheel;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Slf4j
public class WheelHttp {

    /**
     * 查询工字轮信息
     *
     * @param wheelBarcode 条形码
     */
    public static Wheel queryIntermediateVO(String wheelBarcode, int productType) {
        Wheel wheel = null;
        try {
            wheel = PackUtils.toWheel(queryIntermediate(wheelBarcode), productType);
        } catch (Exception ex) {
            log.error("根据轮号查询信息中心数据出错，轮号：{}", wheelBarcode, ex);
        } finally {
            if (wheel == null) {
                wheel = PackUtils.toWheel(queryIntermediate(wheelBarcode), productType);
                log.info("信息中心未查到信息,轮号：{}未查到数据", wheelBarcode);
            }
        }
        return wheel;
    }

    /**
     * 返回结果非三种情况 1查询出错 返回null 2查询成功 无结果 返回new JSONObject() 3 返回查询结果
     *
     * @return 返回查询结果
     */
    public static JSONObject queryIntermediate(String wheelBarcode) {
        List<NameValuePair> list = Collections.singletonList(new BasicNameValuePair("hwheelbarcode", wheelBarcode));
        JSONObject returnJson = null;
        try {
            JSONObject entityJson = BaseHttp.get(AppSetUrl.wheel_url, list);

            if (Objects.nonNull(entityJson) && entityJson.getIntValue("code") == 0 && "success".equals(entityJson.getString("msg"))) {
                // 执行成功了查询
                JSONObject result = entityJson.getJSONObject("result");
                returnJson = CollectionUtils.isEmpty(result) ? new JSONObject() : result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnJson;
    }
}
